package com.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.HashMap;
import java.util.Map;

/**
 * @description
 * @author: wangtao
 * @date:17:52 2018/12/6
 * @email:taow02@jumei.com
 */
public class ClientConnectClz {

	private static Map<String, MqttClient> clientMap = new HashMap<>();

	public static MqttClient connect(String clientid) {
		try {
			MqttConnectOptions options = new MqttConnectOptions();
			final String HOST = "tcp://" + "192.168.2.11" + ":" + "1883";
			MqttClient client = new MqttClient(HOST, clientid, new MemoryPersistence());
			options.setUserName(clientid);
			options.setPassword("11111".toCharArray());
			// 设置超时时间
			options.setConnectionTimeout(10);
			// 设置会话心跳时间
			options.setKeepAliveInterval(20);//心跳时间不必太长
			client.setCallback(new DefaultMqttCallback(clientid));
			client.connect(options);
			client.subscribe(clientid);
			clientMap.put(clientid, client);
			return client;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void sendMqttMsg(String clientId, String sendTo, MqttMessage msg) {
		try {
			clientMap.get(clientId).publish(sendTo, msg);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	public static MqttClient getClient(String clientId) {
		return clientMap.get(clientId);
	}
}
